package com.cn.algorithm.one.map;


import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;

public class HashMap<K ,V> implements Map<K, V> {

    public static final boolean RED = false;

    public static final boolean BLACK =true;

    public static final float BALANCE_FACTOR = 0.75f;

    public static final int DEFAULT_CAPACITY = 1 << 4;

    Node<K, V>[] tables;

    int size;

    public HashMap() {
        tables = new Node[DEFAULT_CAPACITY];
    }

    @Override
    public int size() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public void clear() {
        for (int i= 0; i < tables.length; i++) {
            tables[i] = null;
        }
        size = 0;
    }

    @Override
    public V put(K key, V value) {
        resize();
        int index = index(key);
        if (tables[index] == null) {
            tables[index] = createNode(key, value, null);
            size++;
            afterPut(tables[index]);
            return null;
        }
        Node<K, V> node = tables[index];
        Node<K, V> parent = null;
        int cmp = -1;
        Node<K, V> result = null;
        boolean searched = false;
        int h1 = hash(key);
        do {
            parent = node;
            K k2 = node.key;
            int h2 = node.hash;
            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
            } else if (Objects.equals(key, k2)) {
                cmp = 0;
            } else if (key != null && k2 != null && key instanceof Comparable &&
            key.getClass() == k2.getClass() && (cmp = ((Comparable<K>)key).compareTo(k2)) != 0) {

            } else if (searched){
                cmp = System.identityHashCode(key) - System.identityHashCode(k2);
            } if ((node.left != null && (result = node(node.left, key)) != null) ||
                    (node.right != null && (result = node(node.right, key)) != null)) {
                cmp = 0;
                node = result;
            } else {
                cmp = System.identityHashCode(key) - System.identityHashCode(k2);
            }
            if (cmp > 0) {
                node = node.right;
            } else if (cmp < 0) {
                node = node.left;
            } else {
                V oldValue = node.value;
                node.key = key;
                node.value = value;
                node.hash = h1;
                return oldValue;
            }
        } while (node != null);
        Node<K, V> newNode = createNode(key, value, parent);
        if (cmp > 0) {
            parent.right = newNode;
        } else {
            parent.left = newNode;
        }
        size++;
        afterPut(newNode);
        return null;
    }

    @Override
    public V get(K key) {
        Node<K, V> node = node(tables[index(key)], key);
        return node != null ? node.value : null;
    }

    @Override
    public V remove(K key) {
        Node<K, V> node = node(tables[index(key)], key);
        if (node == null) {
            return null;
        }
        size--;
        Node<K, V> willNode = node;
        V oldValue = node.value;
        if (node.hasTwoChildren()) {
            Node<K, V> successor = successor(node);
            node.key = successor.key;
            node.value = successor.value;
            node.hash = successor.hash;
            node = successor;
        }
        Node<K, V> replaceNode = node.left != null ? node.left : node.right;
        if (replaceNode != null) {
            replaceNode.parent = node.parent;
            if (node.parent == null) {
                tables[index(node)] = replaceNode;
            } else if (node.isLeftChild()) {
                node.parent.left = replaceNode;
            } else {
                node.parent.right = replaceNode;
            }
            afterRemove(replaceNode);
        } else if (node.parent == null) {
            tables[index(node)] = null;
            afterRemove(node);
        } else {
            if (node.isLeftChild()) {
                node.parent.left = null;
            } else {
                node.parent.right = null;
            }
            afterRemove(node);
        }
        afterRemoveFixLinkedMap(willNode, node);
        return oldValue;
    }

    @Override
    public boolean containsKey(K key) {
        return node(tables[index(key)], key) != null;
    }

    @Override
    public boolean containsValue(V value) {
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0 ; i < tables.length; i++) {
            if (tables[i] != null) {
                queue.offer(tables[i]);
                while (!queue.isEmpty()) {
                    Node<K, V> node = queue.poll();
                    if (Objects.equals(value, node.value)) {
                        return true;
                    }
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                }
            }
        }
        return false;
    }

    @Override
    public void traversal(VisitMap<K, V> visit) {
        if (visit == null) {
            return;
        }
        for (int i = 0; i < tables.length; i++) {
            preorder(visit, tables[i]);
        }
    }

    public void preorder(VisitMap<K, V> visit, Node<K, V> node) {
        if (node == null || visit.stop) {
            return;
        }
        visit.stop = visit.visit(node.key, node.value);
        preorder(visit, node.left);
        preorder(visit, node.right);
    }

    public Node<K, V> createNode(K key, V value, Node<K, V> parent) {
        return new Node<>(key, value, parent);
    }

    public Node<K, V> successor(Node<K, V> node) {
        if (node == null) {
            return null;
        }
        Node<K, V> right = node.right;
        if (right != null) {
            while (right.left != null) {
                right = right.left;
            }
            return right;
        }
        while (node.parent != null && node.isRightChild()){
            node = node.parent;
        }
        return node.parent;
    }

    public void afterPut(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        if (parent == null) {
            black(node);
            return;
        }
        if (isBlack(parent)) {
            return;
        }
        Node<K, V> uncle = parent.sibling();
        Node<K, V> grand = red(parent.parent);
        if (isRed(uncle)) {
            black(uncle);
            black(parent);
            afterPut(grand);
            return;
        }
        if (parent.isLeftChild()) {
            if (node.isRightChild()) {
                black(node);
                rotateLeft(parent);
            } else {
                black(parent);
            }
            rotateRight(grand);
        } else {
            if (node.isLeftChild()) {
                black(node);
                rotateRight(parent);
            } else {
                black(parent);
            }
            rotateLeft(grand);
        }
    }

    public void afterRemoveFixLinkedMap(Node<K, V> willNode, Node<K, V> removeNode) {

    }

    public void afterRemove(Node<K, V> node) {
        Node<K, V> parent = node.parent;
        if (parent == null) {
            return;
        }
        if (isRed(node)) {
            black(node);
            return;
        }
        boolean left = parent.left == null || node.isLeftChild();
        Node<K, V> sibling = left ? parent.right : parent.left;
        if (left) {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateLeft(parent);
                sibling = parent.right;
            }
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentColor = isBlack(parent);
                red(sibling);
                black(parent);
                if (parentColor) {
                    afterRemove(parent);
                }
            } else {
                if (isBlack(sibling.right)) {
                    rotateRight(sibling);
                    sibling = parent.right;
                }
                colorOf(sibling, color(parent));
                black(parent);
                black(sibling.right);
                rotateLeft(parent);
            }
        } else {
            if (isRed(sibling)) {
                black(sibling);
                red(parent);
                rotateRight(parent);
                sibling = parent.left;
            }
            if (isBlack(sibling.left) && isBlack(sibling.right)) {
                boolean parentColor = isBlack(parent);
                red(sibling);
                black(parent);
                if (parentColor) {
                    afterRemove(parent);
                }
            } else {
                if (isBlack(sibling.left)) {
                    rotateLeft(sibling);
                    sibling = parent.left;
                }
                colorOf(sibling, color(parent));
                black(parent);
                black(sibling.left);
                rotateRight(parent);
            }
        }
    }

    public Node<K, V> node(Node<K, V> node, K key) {
        int h1 = hash(key);
        int cmp = -1;
        Node<K, V> result = null;
        while (node != null) {
            int h2 = node.hash;
            K k2 = node.key;
            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
            } else if (Objects.equals(key, k2)) {
                cmp = 0;
            } else if (key != null && k2 != null && key instanceof Comparable &&
                    key.getClass() == k2.getClass() && (cmp = ((Comparable<K>)key).compareTo(k2)) != 0) {

            } else if (node.left != null && (result = node(node.left, key)) != null) {
                node = result;
            } else {
                cmp = 1;
            }
            if (cmp == 0) {
                return node;
            } else if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        }
        return null;
    }

    public void resize() {
        if (size / tables.length <= BALANCE_FACTOR) {
            return;
        }
        Node<K, V>[] oldTables = tables;
        tables = new Node[tables.length << 1];
        Queue<Node<K, V>> queue = new LinkedList<>();
        for (int i = 0 ; i < oldTables.length; i++) {
            if (oldTables[i] != null) {
                queue.offer(oldTables[i]);
                while (!queue.isEmpty()) {
                    Node<K, V> node = queue.poll();
                    if (node.left != null) {
                        queue.offer(node.left);
                    }
                    if (node.right != null) {
                        queue.offer(node.right);
                    }
                    adjustNode(node);
                }
            }
        }
    }

    public void adjustNode(Node<K, V> oldNode) {
        oldNode.parent = null;
        oldNode.left = null;
        oldNode.right = null;
        oldNode.color = RED;
        int index = index(oldNode);
        if (tables[index] == null) {
            tables[index] = oldNode;
            afterPut(oldNode);
            return;
        }
        Node<K, V> node = tables[index];
        int cmp = -1;
        K k1 = oldNode.key;
        int h1 = oldNode.hash;
        Node<K, V> parent = null;
        do {
            parent = node;
            int h2 = node.hash;
            K k2 = node.key;
            if (h1 > h2) {
                cmp = 1;
            } else if (h1 < h2) {
                cmp = -1;
            } else if (k1 != null && k2 != null && k1 instanceof Comparable &&
                   k1.getClass() == k2.getClass() && (cmp = ((Comparable<K>)k1).compareTo(k2)) != 0) {
            } else {
                cmp = System.identityHashCode(k1) - System.identityHashCode(k2);
            }
            if (cmp > 0) {
                node = node.right;
            } else {
                node = node.left;
            }
        } while (node != null);
        oldNode.parent = parent;
        if (cmp > 0) {
            parent.right = oldNode;
        } else {
            parent.left = oldNode;
        }
        afterPut(oldNode);
    }

    public int hash(K key) {
        int hashCode = key == null ? 0 : key.hashCode();
        return hashCode ^ (hashCode >>> 16);
    }

    public int index(K key) {
        return hash(key) & (tables.length - 1);
    }

    public int index(Node<K, V> node) {
        return node.hash & (tables.length - 1);
    }


    public void rotateLeft(Node<K, V> grand) {
        Node<K, V> parent = grand.right;
        Node<K, V> child = parent.left;
        parent.left = grand;
        grand.right = child;
        afterRotate(grand, parent, child);
    }

    public void rotateRight(Node<K, V> grand) {
        Node<K, V> parent = grand.left;
        Node<K, V> child = parent.right;
        parent.right = grand;
        grand.left = child;
        afterRotate(grand, parent, child);
    }

    public void afterRotate(Node<K, V> grand, Node<K, V> parent, Node<K, V> child) {
        parent.parent = grand.parent;
        if (grand.parent == null) {
            tables[index(grand)] = parent;
        } else if (grand.isLeftChild()) {
            grand.parent.left = parent;
        } else {
            grand.parent.right = parent;
        }
        grand.parent = parent;
        if (child != null) {
            child.parent = grand;
        }
    }

    public Node<K, V> colorOf(Node<K, V> node, boolean color) {
        if (node == null) {
            return null;
        }
        node.color = color;
        return node;
    }

    public boolean color(Node<K, V> node) {
        if (node == null) {
            return BLACK;
        }
        return node.color;
    }

    public Node<K, V> red(Node<K, V> node) {
        return colorOf(node, RED);
    }

    public Node<K, V> black(Node<K, V> node) {
        return colorOf(node, BLACK);
    }

    public boolean isRed(Node<K, V> node) {
        return color(node) == RED;
    }

    public boolean isBlack(Node<K, V> node) {
        return color(node) == BLACK;
    }

    public static class Node<K, V> {

        boolean color = RED;

        int hash;

        K key;

        V value;

        Node<K, V> parent;

        Node<K, V> left;

        Node<K, V> right;

        public Node(K key, V value, Node<K, V> parent) {
            int hashCode = key == null ? 0 : key.hashCode();
            this.hash = hashCode ^ (hashCode >>> 16);
            this.key = key;
            this.value = value;
            this.parent = parent;
        }

        public boolean isLeftChild() {
            return parent != null && this == parent.left;
        }

        public boolean isRightChild() {
            return parent != null && this == parent.right;
        }

        public boolean hasTwoChildren() {
            return left != null && right != null;
        }

        public Node<K, V> sibling() {
            if (parent == null) {
                return null;
            } else if (this.isLeftChild()) {
                return parent.right;
            } else {
                return parent.left;
            }
        }
    }

    public static void main(String[] args) {
        Integer data[] = new Integer[]{
                // 7, 4
                // 7, 4, 9
                // 7, 4, 9, 5
                // 7, 4, 9, 2
                // 7, 4, 9, 2, 8
                7, 4, 8, 9, 10, 2, 3, 1
        };

        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < data.length; i++) {
            map.put(data[i], data[i]);
        }
        System.out.println(map.size());
        System.out.println("----------------------------------");
        map.remove(1);
        System.out.println(map.size());
        map.traversal(new VisitMap<Integer, Integer>() {
            @Override
            public boolean visit(Integer key, Integer value) {
                System.out.println("key:" + key + ", value:" + value);
                return false;
            }
        });

    }
}
